package com.inspur.cloud.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

public class HttpUtil {

    /**
     * 获取POST方法request的请求体
     * @param httpServletRequest
     * @return
     */
    public static String getRequestBody(HttpServletRequest httpServletRequest){
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader=null;
        try{
            reader = httpServletRequest.getReader();
            String line=null;
            while((line = reader.readLine())!=null){
                buffer.append(line);
            }
        }catch(java.io.IOException e){
            e.printStackTrace();
        }finally{
            if(null!=reader){
                try {
                    reader.close();
                } catch (java.io.IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String res = buffer.toString();
        return res;
    }

    /**
     * 获取客户端IP
     * @param request
     * @return
     */
    public static String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");

        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
